// ==================== 门店列表页组件 ====================
const ShopsPage = {
    props: ['shops', 'sensors'],
    emits: ['viewShop'],
    template: `
        <div class="shops-page">
            <div class="page-header">
                <h1><el-icon><Shop /></el-icon> 门店管理</h1>
                <div class="page-actions">
                    <el-input 
                        v-model="searchText" 
                        placeholder="搜索门店..." 
                        :prefix-icon="Search"
                        style="width: 300px;"
                        clearable
                    />
                </div>
            </div>
            
            <el-table 
                :data="filteredShops" 
                stripe 
                :default-sort="{ prop: 'id', order: 'ascending' }"
                @row-click="(row) => $emit('viewShop', row)"
                style="cursor: pointer;"
            >
                <el-table-column prop="id" label="ID" width="80" sortable />
                <el-table-column prop="name" label="门店名称" width="200" sortable />
                <el-table-column prop="address" label="地址" min-width="250" />
                <el-table-column prop="manager" label="负责人" width="120" />
                <el-table-column prop="phone" label="联系电话" width="150" />
                <el-table-column label="传感器状态" width="200">
                    <template #default="{ row }">
                        <div class="sensor-status-inline">
                            <el-tag type="success" size="small">
                                关闭: {{ getShopClosedCount(row.id) }}
                            </el-tag>
                            <el-tag type="warning" size="small">
                                开启: {{ getShopOpenCount(row.id) }}
                            </el-tag>
                            <el-tag type="danger" size="small">
                                离线: {{ getShopOfflineCount(row.id) }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getShopStatusType(row)">
                            {{ getShopStatusText(row) }}
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    `,
    setup(props) {
        const { ref, computed } = Vue;
        const { Search } = ElementPlusIconsVue;
        
        const searchText = ref('');
        
        const filteredShops = computed(() => {
            if (!searchText.value) return props.shops;
            const text = searchText.value.toLowerCase();
            return props.shops.filter(shop => 
                shop.name.toLowerCase().includes(text) ||
                shop.address.toLowerCase().includes(text) ||
                (shop.manager && shop.manager.toLowerCase().includes(text))
            );
        });
        
        const getShopSensors = (shopId) => {
            return props.sensors.filter(s => s.shopId === shopId);
        };
        
        const getShopClosedCount = (shopId) => {
            return getShopSensors(shopId).filter(s => s.currentState === 'closed').length;
        };
        
        const getShopOpenCount = (shopId) => {
            return getShopSensors(shopId).filter(s => s.currentState === 'open').length;
        };
        
        const getShopOfflineCount = (shopId) => {
            return getShopSensors(shopId).filter(s => s.isOffline).length;
        };
        
        const getShopStatusType = (shop) => {
            const offlineCount = getShopOfflineCount(shop.id);
            const openCount = getShopOpenCount(shop.id);
            
            if (offlineCount > 0) return 'danger';
            if (openCount > 0) return 'warning';
            return 'success';
        };
        
        const getShopStatusText = (shop) => {
            const offlineCount = getShopOfflineCount(shop.id);
            const openCount = getShopOpenCount(shop.id);
            
            if (offlineCount > 0) return '异常';
            if (openCount > 0) return '未关闭';
            return '正常';
        };
        
        return {
            searchText,
            filteredShops,
            getShopClosedCount,
            getShopOpenCount,
            getShopOfflineCount,
            getShopStatusType,
            getShopStatusText,
            Search,
        };
    }
};

// ==================== 传感器列表页组件 ====================
const SensorsPage = {
    props: ['sensors'],
    emits: ['viewSensor'],
    template: `
        <div class="sensors-page">
            <div class="page-header">
                <h1><el-icon><Cpu /></el-icon> 传感器管理</h1>
                <div class="page-actions">
                    <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 150px; margin-right: 10px;">
                        <el-option label="全部" value="all" />
                        <el-option label="在线" value="online" />
                        <el-option label="离线" value="offline" />
                    </el-select>
                    <el-select v-model="stateFilter" placeholder="开关状态" style="width: 150px; margin-right: 10px;">
                        <el-option label="全部" value="all" />
                        <el-option label="已关闭" value="closed" />
                        <el-option label="已开启" value="open" />
                        <el-option label="未知" value="unknown" />
                    </el-select>
                    <el-input 
                        v-model="searchText" 
                        placeholder="搜索传感器ID..." 
                        :prefix-icon="Search"
                        style="width: 300px;"
                        clearable
                    />
                </div>
            </div>
            
            <el-table 
                :data="filteredSensors" 
                stripe
                @row-click="(row) => $emit('viewSensor', row)"
                style="cursor: pointer;"
            >
                <el-table-column prop="sensorId" label="传感器ID" width="200" />
                <el-table-column prop="shopName" label="所属门店" width="180" />
                <el-table-column prop="location" label="安装位置" width="150" />
                <el-table-column label="当前状态" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getStateType(row.currentState)" size="small">
                            {{ getStateText(row.currentState) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="在线状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.isOffline ? 'danger' : 'success'" size="small">
                            {{ row.isOffline ? '离线' : '在线' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="电池电量" width="120">
                    <template #default="{ row }">
                        <el-progress 
                            :percentage="row.batteryLevel || 0" 
                            :color="getBatteryColor(row.batteryLevel)"
                            :format="() => (row.batteryLevel || 0) + '%'"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="信号强度" width="100">
                    <template #default="{ row }">
                        <span :style="{ color: getSignalColor(row.rssi) }">
                            {{ row.rssi ? row.rssi + ' dBm' : '-' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="lastOnlineTime" label="最后在线" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.lastOnlineTime) }}
                    </template>
                </el-table-column>
            </el-table>
        </div>
    `,
    setup(props) {
        const { ref, computed } = Vue;
        const { Search } = ElementPlusIconsVue;
        
        const searchText = ref('');
        const statusFilter = ref('all');
        const stateFilter = ref('all');
        
        const filteredSensors = computed(() => {
            let result = props.sensors;
            
            // 在线状态筛选
            if (statusFilter.value === 'online') {
                result = result.filter(s => !s.isOffline);
            } else if (statusFilter.value === 'offline') {
                result = result.filter(s => s.isOffline);
            }
            
            // 开关状态筛选
            if (stateFilter.value !== 'all') {
                result = result.filter(s => s.currentState === stateFilter.value);
            }
            
            // 搜索
            if (searchText.value) {
                const text = searchText.value.toLowerCase();
                result = result.filter(s => 
                    s.sensorId.toLowerCase().includes(text) ||
                    (s.shopName && s.shopName.toLowerCase().includes(text))
                );
            }
            
            return result;
        });
        
        const getStateType = (state) => {
            if (state === 'closed') return 'success';
            if (state === 'open') return 'danger';
            return 'info';
        };
        
        const getStateText = (state) => {
            if (state === 'closed') return '已关闭';
            if (state === 'open') return '已开启';
            return '未知';
        };
        
        const getBatteryColor = (level) => {
            if (level >= 60) return '#67c23a';
            if (level >= 30) return '#e6a23c';
            return '#f56c6c';
        };
        
        const getSignalColor = (rssi) => {
            if (!rssi) return '#909399';
            if (rssi >= -60) return '#67c23a';
            if (rssi >= -80) return '#e6a23c';
            return '#f56c6c';
        };
        
        const formatTime = (time) => {
            if (!time) return '-';
            return new Date(time).toLocaleString('zh-CN');
        };
        
        return {
            searchText,
            statusFilter,
            stateFilter,
            filteredSensors,
            getStateType,
            getStateText,
            getBatteryColor,
            getSignalColor,
            formatTime,
            Search,
        };
    }
};

// ==================== 电力设备页组件 ====================
const PowerDevicesPage = {
    props: ['powerDevices'],
    template: `
        <div class="power-devices-page">
            <div class="page-header">
                <h1><el-icon><Lightning /></el-icon> 电力设备监控</h1>
                <div class="page-actions">
                    <el-button type="primary" :icon="Refresh" @click="refreshData">刷新数据</el-button>
                </div>
            </div>
            
            <!-- 统计概览 -->
            <div class="stats-overview">
                <div class="stat-item">
                    <div class="stat-value">{{ totalDevices }}</div>
                    <div class="stat-label">设备总数</div>
                </div>
                <div class="stat-item stat-success">
                    <div class="stat-value">{{ powerOffDevices }}</div>
                    <div class="stat-label">已断电</div>
                </div>
                <div class="stat-item stat-danger">
                    <div class="stat-value">{{ powerOnDevices }}</div>
                    <div class="stat-label">未断电</div>
                </div>
                <div class="stat-item stat-warning">
                    <div class="stat-value">{{ offlineDevices }}</div>
                    <div class="stat-label">离线设备</div>
                </div>
            </div>
            
            <!-- 设备列表 -->
            <el-card class="device-list-card">
                <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span>设备列表</span>
                        <el-tag :type="allPowerOff ? 'success' : 'danger'">
                            {{ allPowerOff ? '全部断电' : '存在未断电设备' }}
                        </el-tag>
                    </div>
                </template>
                
                <div class="power-devices-grid">
                    <div 
                        v-for="device in powerDevices" 
                        :key="device.merchantId"
                        class="power-device-card"
                        :class="getPowerDeviceCardClass(device)"
                    >
                        <div class="device-header">
                            <div class="device-info">
                                <h3>{{ device.merchantName || device.merchantId }}</h3>
                                <span class="device-id">ID: {{ device.merchantId }}</span>
                            </div>
                            <el-tag 
                                :type="device.allPowerOff ? 'success' : 'danger'" 
                                size="large"
                            >
                                {{ device.allPowerOff ? '已断电' : '未断电' }}
                            </el-tag>
                        </div>
                        
                        <div class="device-body">
                            <div class="power-status">
                                <el-icon size="48" :color="device.allPowerOff ? '#67c23a' : '#f56c6c'">
                                    <Lightning />
                                </el-icon>
                                <div class="status-text">
                                    {{ device.allPowerOff ? '电源已断开' : '电源连接中' }}
                                </div>
                            </div>
                            
                            <div class="device-details">
                                <div class="detail-item">
                                    <span class="label">上次查询结果:</span>
                                    <el-tag :type="device.allPowerOff ? 'success' : (device.hasData ? 'danger' : 'info')" size="small">
                                        {{ device.hasData ? (device.allPowerOff ? '全部断电' : '部分有电') : '暂无查询记录' }}
                                    </el-tag>
                                </div>
                                <div class="detail-item">
                                    <span class="label">上次查询时间:</span>
                                    <span class="value">{{ formatTime(device.updateTime) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <el-empty v-if="!powerDevices || powerDevices.length === 0" description="暂无电力设备数据" />
            </el-card>
        </div>
    `,
    setup(props, { emit }) {
        const { computed } = Vue;
        const { Refresh } = ElementPlusIconsVue;
        
        const totalDevices = computed(() => props.powerDevices?.length || 0);
        
        const powerOffDevices = computed(() => 
            props.powerDevices?.filter(d => d.allPowerOff).length || 0
        );
        
        const powerOnDevices = computed(() => 
            props.powerDevices?.filter(d => !d.allPowerOff && d.hasData).length || 0
        );
        
        const offlineDevices = computed(() => 
            props.powerDevices?.filter(d => !d.hasData).length || 0
        );
        
        const allPowerOff = computed(() => 
            props.powerDevices?.every(d => d.allPowerOff || !d.hasData) || false
        );
        
        const getPowerDeviceCardClass = (device) => {
            if (!device.hasData) return 'device-offline';
            return device.allPowerOff ? 'device-power-off' : 'device-power-on';
        };
        
        const formatTime = (time) => {
            if (!time) return '无数据';
            return new Date(time).toLocaleString('zh-CN');
        };
        
        const refreshData = () => {
            emit('refresh');
        };
        
        return {
            Refresh,
            totalDevices,
            powerOffDevices,
            powerOnDevices,
            offlineDevices,
            allPowerOff,
            getPowerDeviceCardClass,
            formatTime,
            refreshData,
        };
    }
};

// ==================== 告警列表页组件 ====================
const AlarmsPage = {
    props: ['alarms'],
    emits: ['confirmAlarm'],
    template: `
        <div class="alarms-page">
            <div class="page-header">
                <h1><el-icon><Bell /></el-icon> 告警中心</h1>
                <el-tag type="danger" size="large">
                    未确认: {{ alarms.length }}
                </el-tag>
            </div>
            
            <el-table :data="alarms" stripe>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="shopName" label="门店" width="180" />
                <el-table-column prop="sensorId" label="传感器ID" width="200" />
                <el-table-column label="告警类型" width="150">
                    <template #default="{ row }">
                        <el-tag :type="getAlarmTypeTag(row.alarmType).type">
                            {{ getAlarmTypeTag(row.alarmType).text }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="alarmMessage" label="告警信息" min-width="250" />
                <el-table-column prop="alarmTime" label="告警时间" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.alarmTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button 
                            type="primary" 
                            size="small"
                            @click.stop="$emit('confirmAlarm', row)"
                        >
                            确认
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    `,
    setup() {
        const getAlarmTypeTag = (type) => {
            const map = {
                'SWITCH_NOT_CLOSED': { text: '开关未关闭', type: 'warning' },
                'SENSOR_OFFLINE': { text: '传感器离线', type: 'danger' },
            };
            return map[type] || { text: type, type: 'info' };
        };
        
        const formatTime = (time) => {
            if (!time) return '-';
            return new Date(time).toLocaleString('zh-CN');
        };
        
        return {
            getAlarmTypeTag,
            formatTime,
        };
    }
};

// 导出组件
if (typeof window !== 'undefined') {
    window.ShopsPage = ShopsPage;
    window.SensorsPage = SensorsPage;
    window.PowerDevicesPage = PowerDevicesPage;
    window.AlarmsPage = AlarmsPage;
}

